package com.demo.图.model;

import cn.hutool.core.lang.Console;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 图的定义
 * @author cl
 */
@Getter
@Setter
public class Graph<T> {
    /** 图的节点 */
    public Map<T, Vertex<T>> vertexMap = new HashMap<>();
    /** 图的边 */
    public HashSet<Edge<T>> edges = new HashSet<>();

    public Graph() {}

    public Graph<T> putVertex(T data, Vertex<T> obj) {
        this.vertexMap.put(data, obj);
        return this;
    }

    public Graph<T> addEdge(Edge<T> edge) {
        edges.add(edge);
        return this;
    }

    /** 打印图的信息 */
    public void print() {
        Console.log("图的节点有 {} 个， 边有 {} 个：", this.vertexMap.size(), this.edges.size());
        for (Map.Entry<T, Vertex<T>> entry : this.vertexMap.entrySet()) {
            StringBuilder stringBuilder = new StringBuilder("节点: ");
            stringBuilder.append(entry.getKey() + " in: " + entry.getValue().in + " out: " + entry.getValue().out + "   \t\t--->\t ");
            for (Vertex ver : entry.getValue().nexts) {
                stringBuilder.append(ver.data + ", ");
            }
            Console.log(stringBuilder.toString());
        }
        Set<Edge> alreadyPrint = new HashSet<>();
        for (Edge edge : this.edges) {
            for (Edge tmp : this.edges) {
                if (edge.from == tmp.to && edge.to == tmp.from && !alreadyPrint.contains(edge)) {
                    Console.log("边 {} <--> {}  \t\t： 权 {}", edge.from.data, edge.to.data, edge.weight);
                    alreadyPrint.add(edge);
                    alreadyPrint.add(tmp);
                    break;
                }
            }

            if (!alreadyPrint.contains(edge)) {
                Console.log("边 {} --> {}  \t\t： 权 {}", edge.from.data, edge.to.data, edge.weight);
            }
        }
    }
}
